import Wxml2Canvas from '../../src/index';
import * as echarts from '../../components/ec-canvas/echarts.min'
import cache from '../../api/cache'
import {
  request
} from "../../requests/post.js"
const util = require('../../utils/util.js')
var app = getApp();
let interstitialAd = null
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    avatarUrl: defaultAvatarUrl,
    theme: wx.getSystemInfoSync().theme,
    loadFlag: false,
    topTabList: [
      // {
      //   icon: '',
      //   name: '日常记录',
      //   id: '1'
      // },
      // {
      //   icon: '',
      //   name: '报告夹',
      //   id: '2'
      // },
      // {
      //   icon: '',
      //   name: '文章科谱',
      //   id: '3'
      // },
      {
        icon: '',
        name: '指标记录',
        id: '4'
      },
    ],
    topTabId: '4',
    cardDataList: [

    ],
    listShowFlag: false,
    // canIUseGetUserProfile: true,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    iosDialog2: false,
    userInfo: [],
    nickName: "",
    ec: {
      disableTouch: true,
      disableTouch: true
    },
    gCanvas: null
  },
  initChart(id, option) {
    // 绑定组件（ec-canvas标签的id）
    let that = this
    let ec_canvas = this.selectComponent(`#${id}`);
    // if(option.xData === null ) {
    //   ec_canvas.seto
    // }
    console.log("ec_canvas")
    ec_canvas.init((canvas, width, height, dpr) => {
      this.setData({
        gCanvas: canvas
      })
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // 解决模糊显示的问题
      })
      // echart表格的内容配置
      var myoption1 = {
        title: {},
        tooltip: {
          trigger: 'none',
          show: true,
          showContent: false,
          triggerOn: 'mousemove'
        }
      }
      var myoption = {
        title: {},
        tooltip: {
          trigger: 'none',
          show: true,
          showContent: false,
          triggerOn: 'mousemove'
        },
        xAxis: {
          type: 'category',
          boundaryGap: ['20%', '20%'],
          data: [],
          axisTick: {
            alignWithLabel: true,
            show: false
          },
          axisLine: {
            show: false
          },
          axisLabel: {
            show: false, //隐藏刻度值
          },
        },
        yAxis: {
          type: 'value',
          splitLine: {
            show: false
          },
          axisLine: {
            show: false
          },
          axisLabel: {
            show: false, //隐藏刻度值
          },
          axisTick: {
            show: false, //刻度线
          }
        },
        grid: {
          top: 30,
          left: '0%',
          right: '0%',
          bottom: '25%',
          containLabel: true
        },
        // dataZoom: [
        //   {
        //     type: 'inside',
        //     start: 0,
        //     end: 50,
        //     show: false
        //   },
        // ],
        series: [{
          name: 'price',
          type: 'line',
          data: option.xData, // 动态修改的数据

          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 1,
              x2: 0,
              y2: 0,
              colorStops: [{
                offset: 0,
                color: '#fff'
              }, {
                offset: 1,
                color: option.color
              }]

            }
          },
          lineStyle: {
            color: option.color
          },
          symbolSize: 4,
          itemStyle: {
            normal: {
              label: {
                show: true,
                color: option.color
              },
              color: option.color,
            },
            emphasis: {
              color: '#F7CC4F', //hover拐点颜色定义
              borderColor: '#64D68A'
            }
          }
        }]
      }
      if(option.xData === null) {
        chart.setOption(myoption1);
      } else {
        chart.setOption(myoption);
      }
      
      // let _this = this
      //   chart.getZr().on('click', function (params) {
      //     var pointInPixel= [params.offsetX, params.offsetY];
      //     chart.containPixel('grid',pointInPixel)
      //     var pointInGrid=chart.convertFromPixel({seriesIndex:0},pointInPixel);
      //     var xIndex=pointInGrid[0];
      //     var op=chart.getOption();
      //     //获得图表中我们想要的数据
      //     var num=op.series[0].data[xIndex];
      //     _this.setData({
      //       chartNumber: num
      //     })
      // });
      return chart;
    })
  },
  changeTabHandle(e) {
    this.setData({
      topTabId: e.currentTarget.dataset.value.id
    })
  },

  bindDateChange(e) {
    console.log("bindDateChange - " + JSON.stringify(e))
    this.setData({
      nickName: e.detail.value
    })
  },

  goAddRecord() {
    wx.navigateTo({
      url: '../../subpackages/pages/zbqs/addRecord',
    })
  },
  toIndexDetail(e) {
    let indexUserId = e.currentTarget.dataset.value.id
    console.log(indexUserId)
    let userId = this.data.userInfo["id"]
    wx.navigateTo({
      url: '../../subpackages/pages/zbqs/indexD?indexUserId=' + indexUserId.substring(3) + "&userId=" + userId
    })
  },
  // 微信登录
  wxLogin() {
    // let nickName = this.data.nickName
    var timestamp = Date.now();
    timestamp = Math.floor(timestamp / 1000).toString();
    var nickName = "番薯用户" + timestamp
    console.log("nickname - " + nickName)
    if (nickName !== "" && nickName !== null) {
      console.log("nickname - 11")
      var that = this
      wx.login({
        success(res) {
          if (res.code) {
            request({
              url: '/wx/login',
              code: res.code,
              nickName: nickName
            }).then(result => {
              if (result.data.errorCode == 200) {
                cache.setOp(app.globalData.userCacheKey, result.data.data)
                // cache.setOp(app.globalData.tokenKey, result.data.data["token"])
                // app.globalData.token = result.data.data["token"]
                app.globalData.key = result.data.data["key"]
                that.setData({
                  userInfo: result.data.data,
                  hasUserInfo: true
                })
                // 跳转到指标页
                wx.hideLoading()
                that.setData({
                  'listShowFlag': true
                })
                // that.goIndexD()
                that.reload(result.data.data)
              } else {
                wx.hideLoading()
                that.setData({
                  "iosDialog2": true
                })
                console.log('服务器异常')
              }
            }, err => {
              //调用服务端登录接口失败
              wx.hideLoading()
              that.setData({
                "iosDialog2": true
              })
            })
          }
        }
      })
    } else {
      wx.showToast({
        title: '昵称不能为空',
        icon: 'none',
        duration: 2000,
      })
    }

  },

  // 登录授权相当
  onGetUserInfoProfile(e) {
    console.info("onGetUserInfoProfile - " + JSON.stringify(e))
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    const userInfo = e.detail
    var that = this
    // if (userInfo) {
    //获取用户信息
    wx.getUserProfile({
      desc: '用于完状况用户资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        // 1. 小程序通过wx.login()获取code
        wx.login({
          success: function (login_res) {
            // console.info("res - " + JSON.stringify(res))
            console.info("login_res - " + JSON.stringify(login_res))
            // 2. 小程序通过wx.request()发送code到开发者服务器

            wx.showLoading({
              title: '登录中'
            })
            wx.request({
              url: app.globalData.baseUrl + '/wx/login',
              method: 'POST',
              header: {
                'content-type': 'application/json'
              },
              timeout: 5000,
              data: {
                code: login_res.code, //临时登录凭证
                rawData: res.rawData, //用户非敏感信息
                signature: res.signature, //签名
                encrypteData: res.encryptedData, //用户敏感信息
                userInfo: res.userInfo,
                iv: res.iv //解密算法的向量
              },
              success: function (res) {
                if (res.data.errorCode == 200) {
                  cache.setOp(app.globalData.userCacheKey, res.data.data)
                  that.setData({
                    userInfo: res.data.data,
                    hasUserInfo: true
                  })
                  // 跳转到指标页
                  wx.hideLoading()
                  that.setData({
                    'listShowFlag': true
                  })
                  // that.goIndexD()
                  that.reload(res.data.data)
                } else {
                  wx.hideLoading()
                  that.setData({
                    "iosDialog2": true
                  })
                  console.log('服务器异常')
                }
              },
              fail: function (error) {
                //调用服务端登录接口失败
                wx.hideLoading()
                that.setData({
                  "iosDialog2": true
                })
                console.log("fail -" + JSON.stringify(error))
              }
            })

          }
        })
        // 这里延时一秒钟看到效果，关闭加载中效果
        //  wx.hideLoading()
      }
    })
  },
  close() {
    this.setData({
      iosDialog2: false
    });
  },

  saveImg() {
    let path = ''
    this.selectComponent('#ec_250').canvasToTempFilePath({
      success(res) {

        path = res.tempFilePath
        console.log(res.tempFilePath);
      },
      fail(res) {
        console.log(res);
      },
      complete(res) {
        console.log(res);
      }
    }, this);
    setTimeout(() => {
      wx.saveImageToPhotosAlbum({
        filePath: path,
        success(res) {
            wx.showToast({
                title: '保存成功',
                icon: 'success'
            })
        },
        fail () {
            wx.showToast({
                title: '保存失败',
                icon: 'none'
            })
        }
    })
      }, 2000);
    
  },

  toEditIndex() {
    wx.navigateTo({
      url: '../../subpackages/pages/zbqs/addIndex',
    })
  },
  reload(user) {
    var that = this;
    request({
      url: '/wx/getUserCartList',
      userId: user["id"]
    }).then(result => {
      if (result.data.errorCode === 200) {
        console.log("cart " + JSON.stringify(result.data.data))
        that.setData({
          cardDataList: result.data.data
        })
        // 初始化图表
        result.data.data.map(e => {
          console.log("map " + JSON.stringify(e))
          if (e.status !== '0') {
            that.initChart(e.id, {
              xData: e.number,
              color: e.standard
            })
          } 
          else {
            that.initChart(e.id, {
              xData: null,
              color: e.standard
            })
          }
        })
      } else if (result.data.errorCode === 1001001) {
        this.setData({
          'listShowFlag': false
        })
      } else {
        wx.showToast({
          title: result.data.msg,
          icon: 'none',
          duration: 2000,
        })
      }
    })
  },

  // echarts 滚动时
  scroll(e) {},
  // echarts下拉事件
  scrolltolowe() {},

  onReady: function () {
    // console.log("onready - refresh token")
    // this.refreshToken();
    // 在页面onLoad回调事件中创建插屏广告实例
    // if (wx.createInterstitialAd) {
    //   interstitialAd = wx.createInterstitialAd({
    //     adUnitId: 'adunit-0b8e614921a3243f'
    //   })
    //   interstitialAd.onLoad(() => {})
    //   interstitialAd.onError((err) => {})
    //   interstitialAd.onClose(() => {})
    // }
    // if (interstitialAd) {
    //   interstitialAd.show().catch((err) => {
    //     console.error(err)
    //   })
    // }
  },
  onShow: function () {
    console.log("listShowFlag - " + this.data.listShowFlag)
    if (this.data.listShowFlag) {
      this.reload(this.data.userInfo)
    }
  },
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    this.setData({
      avatarUrl,
    })
  },
  refreshToken() {
    console.log("refreshToken")
    let that = this
    request({
      url: '/wx/refresh_token',
      token: app.globalData.token
    }).then(result => {
      if (result.data.errorCode === 200) {
        cache.setOp(app.globalData.tokenKey, result.data.data)
        app.globalData.token = result.data.data
      } else {
        that.setData({
          'listShowFlag': false
        })
      }
    }, err => {
      console.log("refreshToken2")
      that.setData({
        'listShowFlag': false
      })
    })
  },

  onLoad: function (options) {

    this.setData({
      avatarUrl: app.globalData.baseUrl + "/wx/TX.jpg"
    });
    wx.setNavigationBarTitle({
      title: "指标记录" // 新的标题  
    });
    // 判断是否已经登录
    var date = util.formatDate(new Date())
    // var user = cache.getOp("userInfo")
    var user = cache.getOp(app.globalData.userCacheKey)
    // var token = cache.getOp(app.globalData.tokenKey)
    // app.globalData.token = token
    if (user === null) {
      this.setData({
        'listShowFlag': false
      })
      // if(user !== null) {
      //   this.setData({
      //     "nickName":user.nickName
      //   })
      // }
      // wx.navigateTo({
      //   url: '../../subpackages/pages/zbqs/index',
      // })
    } else {
      this.setData({
        "nickName": user.nickName
      })
      console.log("user.key " + user.key)
      if (typeof user.key === "undefined" || user.key === null || user.key === null) {
        this.setData({
          'listShowFlag': false
        })
        return
      }

      app.globalData.key = user.key
      this.setData({
        'userInfo': user,
        'listShowFlag': true,
      })
      // 获取列表数据
      this.setData({
        loadFlag: true
      })
      // this.reload(user)
    }
  },
  onShareTimeline() {

  },
  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '指标记录'
        })
      }, 2000)
    })
    return {
      title: '医学计算',
      path: '/pages/record/fourTabPage',
      promise
    }
  },
})